package com.xxxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxxx.pojo.Menu;
import com.xxxx.pojo.MenuRole;
import com.xxxx.pojo.R;
import com.xxxx.pojo.Role;
import com.xxxx.service.MenuRoleService;
import com.xxxx.service.MenuService;
import com.xxxx.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.PseudoColumnUsage;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author achao
 * @version 1.0
 */

@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuRoleService menuRoleService;


    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public R getAllRoles() {
        return R.success(roleService.list());
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public R addRole(@RequestBody Role role) {

        if (!role.getName().startsWith("ROLE_")) {
            role.setName("ROLE_" + role.getName());
        }
        boolean flag = roleService.save(role);
        return flag ? R.success("添加角色成功！") : R.error("添加角色失败！");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{id}")
    public R deleteRole(@PathVariable Integer id) {
        if (roleService.removeById(id)) {
            return R.success("删除成功！");
        }
        return R.error("删除失败！");
    }

    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public R getAllMenus() {
        List<Menu> menus = menuService.getAllMenus();
        return R.success(menus);
    }

    @ApiOperation(value = "根据角色Id查询菜单")
    @GetMapping("/mid/{rid}")
    public R getMidByRid(@PathVariable Integer rid) {
        LambdaQueryWrapper<MenuRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuRole::getRid, rid);
        List<MenuRole> menuRoles = menuRoleService.list(wrapper);
        List<Integer> ids = menuRoles.stream().map(MenuRole::getMid).collect(Collectors.toList());
        return R.success(ids);
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    public R updateMenuRole(Integer rid, Integer[] mids) {
        return menuRoleService.updateMenuRole(rid, mids);
    }
}
